import {Component, OnInit, ViewChild} from '@angular/core';
import {MaintainModelComponent} from "../../shared/component/maintain-model/maintain-model.component";
import {ActivatedRoute, ParamMap} from "@angular/router";
import {CamManageService} from "../../shared/service/cam-manage.service";
import {Vehicle} from "../../shared/model/vehicle";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {MaintainService} from "../../shared/service/maintain.service";
import {MaintainRecordTableComponent} from "../maintain-record-table/maintain-record-table.component";
import {MaintainRecord} from "../../shared/model/maintainRecord";
import {FormBuilder, FormGroup} from "@angular/forms";
import {MaintainSearchComponent} from "../maintain-search/maintain-search.component";
import {NzModalService} from "ng-zorro-antd";
import {MaintainRecordSearch} from "../../shared/model/maintainRecordSearch";
declare var $:any;

@Component({
  selector: 'app-maintain-record-home',
  templateUrl: './maintain-record-home.component.html',
  styleUrls: ['./maintain-record-home.component.css']
})
export class MaintainRecordHomeComponent implements OnInit {

  vehicle:Vehicle = new Vehicle;
  maintainRecord:MaintainRecord;
  @ViewChild(MaintainModelComponent) modal :MaintainModelComponent;
  @ViewChild(MaintainSearchComponent) searchModal :MaintainSearchComponent;
  startPick1:any;
  endPick1:any;
  flag:string;  //判断新增或修改
  highForm:FormGroup;
  types:any;
  statuses:any = [{
    "id":0,
    "name":"维护中"
  },{
    "id":1,
    "name":"已结束"
  }];

  //选择人员分页
  _current = 1;
  _pageSize = 10;
  _total = 1;
  _dataSet = [];
  _loading = true;
  allCheckbox:boolean = false;
  queryId = "";
  queryName = "";
  type:string;
  vehicleoid:string = "";
  starttime:any = "";
  endtime:any = "";
  typeoid:string = "";
  status:number = -1;
  maintainRecordList:MaintainRecord[] = [];
  searchParam:MaintainRecordSearch = new MaintainRecordSearch; //高级查询条件

  //选择框
  _allChecked = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];


  constructor(private routeInfo:ActivatedRoute,
              private camManageService:CamManageService,
              private singleOpenWinService:SingleOpenWinService,
              private maintainService:MaintainService,
              private fb:FormBuilder,
              private modalService: NzModalService
  ) { }

  ngOnInit() {

    //初始化开始时间
    this.startPick1 = $('#startDate1').datetimepicker({
      // sideBySide: true, //可以同时选择日期和时间
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      ignoreReadonly: true,
      stepping: 30,        //设置最小间隔分钟数
      useCurrent: false,
    });
    this.startPick1.on("dp.change", (e) => {
      //限制结束时间
      $('#endDate1').data("DateTimePicker").minDate(e.date);
    });
    //初始化结束时间
    this.endPick1 = $('#endDate1').datetimepicker({
      // sideBySide: true, //可以同时选择日期和时间
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      ignoreReadonly: true,
      stepping: 30,         //设置最小间隔分钟数
      useCurrent: false,
    });
    this.endPick1.on("dp.change", (e) => {
      //限制开始时间
      $('#startDate1').data("DateTimePicker").maxDate(e.date);
    });

    this.camManageService.oidEvent.subscribe((oid)=>{
      if(oid != ""&& oid != null){
        this.camManageService.getVehicleByOID(oid).then(res=>{
          this.vehicle = res.vehicle;
          this.refreshDataTable();
        });
      }else{
        this.vehicle.oid = null;
        this._dataSet = [];
        this._displayData = [];
        this.maintainRecordList = [];
      }
    });

    this.maintainService.getRecordEvent.subscribe((str)=>{
      this.flag = str[0]; //add:新增,edit:修改,view:查看,list:刷新页面
      if(this.flag==="list"){
        this.maintainHandleCancel();
      }else{
        this.maintainService.getMaintainRecordByOid(str[1]).then(res=>{
          this.vehicle = res.vehicle;
          this.maintainRecord = res.maintainRecord;
          this.maintainShowModal();
        });
      }
    });
    this.createForm();
  }

  /**
   *  维护记录开窗
   */
  maintainIsVisible = false;

  maintainShowModal = () => {
    if(this.vehicle.oid){
      this.modal.vehicle = this.vehicle;
      this.modal.maintainRecord = this.maintainRecord;
      this.modal.flag = this.flag;
      this.modal.ngOnInit();
      this.maintainIsVisible = true;
    }else{
      alert("请先选择车辆！");
    }
  }

  maintainHandleCancel = () => {
    this.modal.vehicleOid = "";
    this.modal.vehicleName = "";
    this.modal.licenseNumber = "";
    this.modal.flag = "";
    this.maintainIsVisible = false;
    this.refreshDataTable();
  }

  addMaintain(){
    this.flag = "add";
    this.maintainShowModal();
  }

  refreshDataTable(){
    this.vehicleoid = this.vehicle.oid;
    this.getTableData();
  }

  createForm(){
    this.highForm = this.fb.group({
      maintainType1:'',
      maintainStatus:'',
      starttime1:'',
      endtime1:''
    });
  }

  //高级查询按钮开窗
  btn_detailedSearch(){
    //初始化高级查询modal
    const subscription = this.modalService.open({
      //title          : '高级查询',
      content        : MaintainSearchComponent,
      onOk() {
      },
      onCancel() {
        // console.log('Click cancel');
      },
      footer         : false,
      componentParams: {
        name: '测试渲染Component'
      }
    });
    //订阅modal框返回值
    subscription.subscribe(result => {
      if(typeof(result)=="object"){
        console.log(result);
        if(result.maintainStatus){
          this.searchParam.status = Number(result.maintainStatus.toString());
        }else{
          this.searchParam.status = -1;
        }
        this.searchParam.vehicle = this.vehicle.oid;
        this.searchParam.starttime = result.starttime1.toString();
        this.searchParam.endtime = result.endtime1.toString();
        this.searchParam.maintainType = result.maintainType1.toString();
        this._current = 1;
        this.checkAllInfo = [];
        this._checkInfo = [];
        this.getTableData();
      }
    });
  }

 //表格方法
  getTableData(){
    //获取home父页面的值,用于高级查询
    if(this.searchParam.vehicle){
      this.vehicleoid = this.searchParam.vehicle;
      this.starttime = this.searchParam.starttime;
      this.endtime = this.searchParam.endtime;
      this.typeoid = this.searchParam.maintainType;
      this.status = this.searchParam.status;
    }
    //查询数据
    this.getDatas();
  }

  getDatas(){
    let start = "";
    if(this.starttime){
      start = this.starttime.substr(0,16);
    }
    let end = "";
    if(this.endtime){
      end = this.endtime.substr(0,16);
    }
    //选择车辆后查询数据
    if(this.vehicleoid){
      this.maintainService.getMaintainRecords(this._current,this._pageSize,this.vehicleoid,start,end,this.typeoid,this.status)
        .then(res=>{
          // console.log(res);
          this.maintainRecordList = res.list;
          this.allCheckbox = false;
          for(let i=0;i<this.maintainRecordList.length;i++){
            //判断维护记录状态
            let statusname = "";
            switch (this.maintainRecordList[i].status) {
              case 0:
                statusname = "维护中";
                break;
              case 1:
                statusname = "已结束";
                break;
            }
            this.maintainRecordList[i].statusname = statusname;
            //判断全选框是否显示
            if(this.maintainRecordList[i].status === 0&&this.maintainRecordList[i].status != 1){
              this.allCheckbox = true;
            }
          }

          this._dataSet = this.maintainRecordList;
          this._loading = false;
          this._total = res.total;
          this._displayData = this.maintainRecordList;
          // console.log(res);

          //查询选中
          for(var i=0;i<this._checkInfo.length;i++){
            if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
              this.checkAllInfo.push(this._checkInfo[i].oid);
            }
          }

          this.select(this.checkAllInfo,this._dataSet);
          this._refreshStatus("","");
        });
    }
  }

  refreshData(reset = false) {
    if (reset) {
      this._current = 1;
    }
    // this._allChecked = false;
    this._loading = true;
    this.getDatas();
  };

  _displayDataChange($event) {
    this._displayData = $event;
  };

  _checkAll(value) {
    if (value) {
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status===0&&this._displayData[i].status!= 1){
          this._displayData[i].checked = true;
        }
      }
    } else {
      this._displayData.forEach(data => data.checked = false);
      for(let i=0;i<this._displayData.length;i++){
        let numb = this.checkAllInfo.indexOf(this._displayData[i].oid);
        if(numb!=-1){
          this.checkAllInfo.splice(numb,1);
        }
      }
    }
    this._refreshStatus("","");
  }

  //当前页checkbox选中判断
  _refreshStatus(event,oid) {
    //全选判断
    if(this._displayData.length>0){
      let count:number = 0;
      let checkNumb:number = 0;
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status ===0&&this._displayData[i].status != 1){
          count++;
          if(this._displayData[i].checked == true){
            checkNumb++;
          }
        }
      }
      if(checkNumb!=0 && count==checkNumb){
        this._allChecked = true;
      }else{
        this._allChecked = false;
      }
    }
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //判断是否有checkbox取消事件
    if(event==false){
      let numb = this.checkAllInfo.indexOf(oid);
      if(numb!=-1){
        this.checkAllInfo.splice(numb,1);
      }
    }
  }

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].oid == selectedData[j]){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }

  delInfo(){
    //将当前页所选会议信息插入所有选择信息变量checkAllInfo中
    for(var i=0;i<this._checkInfo.length;i++){
      if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
        this.checkAllInfo.push(this._checkInfo[i].oid);
      }
    }
    if(this.checkAllInfo.length>0){
      if(confirm("共选择"+this.checkAllInfo.length+"条维护记录，确认结束维护？\n")){
        let oids = "";
        for(let i=0;i<this.checkAllInfo.length;i++){
          oids += this.checkAllInfo[i]+";";
        }
        if(oids){
          this.maintainService.endMaintainRecords(oids).then(res=>{
            alert(res.message);
          });
        }
        this.checkAllInfo = [];
        this._checkInfo = [];
        this.refreshData();
      }
    }else{
      alert("请至少选择一条维护记录！\n");
    }
  }

  endrecord(oid){
    if(confirm("确认结束维护？")){
      this.maintainService.endMaintainRecord(oid);
    }
    this.maintainService.getRecordEvent.emit(["list"]);
  }

  updaterecord(oid){
    this.maintainService.getRecordEvent.emit(["edit",oid]);
  }

  viewrecord(oid){
    this.maintainService.getRecordEvent.emit(["view",oid]);
  }

}
